<template>
  <div class="table-designer">
    <div class="designer-header">
      <div class="header-info">
        <h3>{{ isNew ? '创建新表' : `编辑表: ${table.name}` }}</h3>
        <el-tag v-if="databaseType" :type="databaseType === 'mysql' ? 'primary' : 'success'">
          {{ databaseType.toUpperCase() }}
        </el-tag>
      </div>
      <div class="header-actions">
        <el-button @click="$emit('cancel')">取消</el-button>
        <el-button type="info" @click="previewSQL" :disabled="!isValidTable">
          <el-icon><View /></el-icon>
          预览SQL
        </el-button>
        <el-button type="primary" @click="saveTable" :disabled="!isValidTable">
          <el-icon><Check /></el-icon>
          {{ isNew ? '创建' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="designer-content">
      <!-- 表基本信息 -->
      <el-card class="table-info-card" shadow="never">
        <template #header>
          <span>表信息</span>
        </template>
        
        <el-form :model="tableForm" :rules="tableRules" ref="tableFormRef" label-width="100px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="表名" prop="name">
                <el-input
                  v-model="tableForm.name"
                  placeholder="请输入表名"
                  :disabled="!isNew"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表注释" prop="comment">
                <el-input
                  v-model="tableForm.comment"
                  placeholder="请输入表注释"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="24" v-if="databaseType === 'mysql'">
            <el-col :span="8">
              <el-form-item label="存储引擎">
                <el-select v-model="tableForm.engine" style="width: 100%">
                  <el-option label="InnoDB" value="InnoDB" />
                  <el-option label="MyISAM" value="MyISAM" />
                  <el-option label="Memory" value="Memory" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="字符集">
                <el-select v-model="tableForm.charset" style="width: 100%">
                  <el-option label="utf8mb4" value="utf8mb4" />
                  <el-option label="utf8" value="utf8" />
                  <el-option label="latin1" value="latin1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排序规则">
                <el-select v-model="tableForm.collation" style="width: 100%">
                  <el-option label="utf8mb4_unicode_ci" value="utf8mb4_unicode_ci" />
                  <el-option label="utf8mb4_general_ci" value="utf8mb4_general_ci" />
                  <el-option label="utf8_general_ci" value="utf8_general_ci" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 字段设计 -->
      <el-card class="columns-card" shadow="never">
        <template #header>
          <div class="columns-header">
            <span>字段设计</span>
            <el-button type="primary" size="small" @click="addColumn">
              <el-icon><Plus /></el-icon>
              添加字段
            </el-button>
          </div>
        </template>

        <div class="columns-table">
          <el-table
            :data="tableForm.columns"
            border
            size="small"
            max-height="400"
            empty-text="暂无字段，请添加字段"
          >
            <el-table-column type="index" label="#" width="50" align="center" />
            
            <el-table-column label="字段名" min-width="120">
              <template #default="{ row, $index }">
                <el-input
                  v-model="row.name"
                  placeholder="字段名"
                  size="small"
                  @blur="validateColumnName(row, $index)"
                />
              </template>
            </el-table-column>

            <el-table-column label="数据类型" min-width="120">
              <template #default="{ row }">
                <el-select
                  v-model="row.type"
                  placeholder="选择类型"
                  size="small"
                  style="width: 100%"
                  @change="onColumnTypeChange(row)"
                >
                  <el-option-group
                    v-for="group in dataTypes"
                    :key="group.label"
                    :label="group.label"
                  >
                    <el-option
                      v-for="type in group.options"
                      :key="type.value"
                      :label="type.label"
                      :value="type.value"
                    />
                  </el-option-group>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="长度" width="80">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.length"
                  :min="1"
                  :max="65535"
                  size="small"
                  style="width: 100%"
                  :disabled="!needsLength(row.type)"
                />
              </template>
            </el-table-column>

            <el-table-column label="默认值" min-width="100">
              <template #default="{ row }">
                <el-input
                  v-model="row.defaultValue"
                  placeholder="默认值"
                  size="small"
                />
              </template>
            </el-table-column>

            <el-table-column label="注释" min-width="120">
              <template #default="{ row }">
                <el-input
                  v-model="row.comment"
                  placeholder="字段注释"
                  size="small"
                />
              </template>
            </el-table-column>

            <el-table-column label="属性" width="200">
              <template #default="{ row }">
                <div class="column-attributes">
                  <el-checkbox v-model="row.nullable" size="small">可空</el-checkbox>
                  <el-checkbox v-model="row.primaryKey" size="small" @change="onPrimaryKeyChange(row)">主键</el-checkbox>
                  <el-checkbox v-model="row.autoIncrement" size="small" :disabled="!canAutoIncrement(row)">自增</el-checkbox>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100" align="center">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="removeColumn($index)"
                  circle
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 索引设计 -->
      <el-card class="indexes-card" shadow="never">
        <template #header>
          <div class="indexes-header">
            <span>索引设计</span>
            <el-button type="primary" size="small" @click="addIndex">
              <el-icon><Plus /></el-icon>
              添加索引
            </el-button>
          </div>
        </template>

        <div class="indexes-table">
          <el-table
            :data="tableForm.indexes"
            border
            size="small"
            max-height="200"
            empty-text="暂无索引"
          >
            <el-table-column type="index" label="#" width="50" align="center" />
            
            <el-table-column label="索引名" min-width="120">
              <template #default="{ row }">
                <el-input
                  v-model="row.name"
                  placeholder="索引名"
                  size="small"
                />
              </template>
            </el-table-column>

            <el-table-column label="索引类型" width="120">
              <template #default="{ row }">
                <el-select v-model="row.type" size="small" style="width: 100%">
                  <el-option label="普通索引" value="INDEX" />
                  <el-option label="唯一索引" value="UNIQUE" />
                  <el-option label="全文索引" value="FULLTEXT" v-if="databaseType === 'mysql'" />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="字段" min-width="150">
              <template #default="{ row }">
                <el-select
                  v-model="row.columns"
                  multiple
                  placeholder="选择字段"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="column in tableForm.columns"
                    :key="column.name"
                    :label="column.name"
                    :value="column.name"
                    :disabled="!column.name"
                  />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100" align="center">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="removeIndex($index)"
                  circle
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { View, Check, Plus, Delete } from '@element-plus/icons-vue'

export default {
  name: 'TableDesigner',
  components: {
    View,
    Check,
    Plus,
    Delete
  },
  props: {
    table: {
      type: Object,
      default: () => ({})
    },
    databaseType: {
      type: String,
      default: 'mysql'
    },
    isNew: {
      type: Boolean,
      default: false
    }
  },
  emits: ['save', 'cancel', 'preview-sql'],
  setup(props, { emit }) {
    const tableFormRef = ref()

    // 表单数据
    const tableForm = reactive({
      name: '',
      comment: '',
      engine: 'InnoDB',
      charset: 'utf8mb4',
      collation: 'utf8mb4_unicode_ci',
      columns: [],
      indexes: []
    })

    // 表单验证规则
    const tableRules = {
      name: [
        { required: true, message: '请输入表名', trigger: 'blur' },
        { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '表名只能包含字母、数字和下划线，且不能以数字开头', trigger: 'blur' }
      ]
    }

    // 数据类型选项
    const dataTypes = computed(() => {
      const mysqlTypes = [
        {
          label: '数值类型',
          options: [
            { label: 'TINYINT', value: 'TINYINT' },
            { label: 'SMALLINT', value: 'SMALLINT' },
            { label: 'MEDIUMINT', value: 'MEDIUMINT' },
            { label: 'INT', value: 'INT' },
            { label: 'BIGINT', value: 'BIGINT' },
            { label: 'FLOAT', value: 'FLOAT' },
            { label: 'DOUBLE', value: 'DOUBLE' },
            { label: 'DECIMAL', value: 'DECIMAL' }
          ]
        },
        {
          label: '字符串类型',
          options: [
            { label: 'CHAR', value: 'CHAR' },
            { label: 'VARCHAR', value: 'VARCHAR' },
            { label: 'TEXT', value: 'TEXT' },
            { label: 'MEDIUMTEXT', value: 'MEDIUMTEXT' },
            { label: 'LONGTEXT', value: 'LONGTEXT' }
          ]
        },
        {
          label: '日期时间类型',
          options: [
            { label: 'DATE', value: 'DATE' },
            { label: 'TIME', value: 'TIME' },
            { label: 'DATETIME', value: 'DATETIME' },
            { label: 'TIMESTAMP', value: 'TIMESTAMP' },
            { label: 'YEAR', value: 'YEAR' }
          ]
        },
        {
          label: '其他类型',
          options: [
            { label: 'BOOLEAN', value: 'BOOLEAN' },
            { label: 'JSON', value: 'JSON' },
            { label: 'BLOB', value: 'BLOB' }
          ]
        }
      ]

      const postgresqlTypes = [
        {
          label: '数值类型',
          options: [
            { label: 'SMALLINT', value: 'SMALLINT' },
            { label: 'INTEGER', value: 'INTEGER' },
            { label: 'BIGINT', value: 'BIGINT' },
            { label: 'REAL', value: 'REAL' },
            { label: 'DOUBLE PRECISION', value: 'DOUBLE PRECISION' },
            { label: 'NUMERIC', value: 'NUMERIC' },
            { label: 'SERIAL', value: 'SERIAL' },
            { label: 'BIGSERIAL', value: 'BIGSERIAL' }
          ]
        },
        {
          label: '字符串类型',
          options: [
            { label: 'CHAR', value: 'CHAR' },
            { label: 'VARCHAR', value: 'VARCHAR' },
            { label: 'TEXT', value: 'TEXT' }
          ]
        },
        {
          label: '日期时间类型',
          options: [
            { label: 'DATE', value: 'DATE' },
            { label: 'TIME', value: 'TIME' },
            { label: 'TIMESTAMP', value: 'TIMESTAMP' },
            { label: 'TIMESTAMPTZ', value: 'TIMESTAMPTZ' }
          ]
        },
        {
          label: '其他类型',
          options: [
            { label: 'BOOLEAN', value: 'BOOLEAN' },
            { label: 'JSON', value: 'JSON' },
            { label: 'JSONB', value: 'JSONB' },
            { label: 'UUID', value: 'UUID' }
          ]
        }
      ]

      return props.databaseType === 'mysql' ? mysqlTypes : postgresqlTypes
    })

    // 是否为有效表
    const isValidTable = computed(() => {
      return tableForm.name && tableForm.columns.length > 0 &&
             tableForm.columns.every(col => col.name && col.type)
    })

    // 监听表数据变化
    watch(() => props.table, (newTable) => {
      if (newTable) {
        Object.assign(tableForm, {
          name: newTable.name || '',
          comment: newTable.comment || '',
          engine: newTable.engine || 'InnoDB',
          charset: newTable.charset || 'utf8mb4',
          collation: newTable.collation || 'utf8mb4_unicode_ci',
          columns: newTable.columns ? [...newTable.columns] : [],
          indexes: newTable.indexes ? [...newTable.indexes] : []
        })
      }
    }, { immediate: true })

    // 判断类型是否需要长度
    const needsLength = (type) => {
      const lengthTypes = ['VARCHAR', 'CHAR', 'DECIMAL', 'NUMERIC', 'FLOAT', 'DOUBLE']
      return lengthTypes.includes(type)
    }

    // 判断是否可以自增
    const canAutoIncrement = (column) => {
      const autoIncrementTypes = ['TINYINT', 'SMALLINT', 'MEDIUMINT', 'INT', 'BIGINT', 'INTEGER', 'SERIAL', 'BIGSERIAL']
      return autoIncrementTypes.includes(column.type) && column.primaryKey
    }

    // 添加字段
    const addColumn = () => {
      tableForm.columns.push({
        name: '',
        type: 'VARCHAR',
        length: 255,
        nullable: true,
        primaryKey: false,
        autoIncrement: false,
        defaultValue: '',
        comment: ''
      })
    }

    // 移除字段
    const removeColumn = (index) => {
      tableForm.columns.splice(index, 1)
    }

    // 验证字段名
    const validateColumnName = (column, index) => {
      if (!column.name) return
      
      const duplicateIndex = tableForm.columns.findIndex((col, i) => 
        i !== index && col.name === column.name
      )
      
      if (duplicateIndex !== -1) {
        ElMessage.warning('字段名不能重复')
        column.name = ''
      }
    }

    // 字段类型变化
    const onColumnTypeChange = (column) => {
      // 重置长度
      if (needsLength(column.type)) {
        if (column.type === 'VARCHAR') {
          column.length = 255
        } else if (column.type === 'CHAR') {
          column.length = 50
        } else if (['DECIMAL', 'NUMERIC'].includes(column.type)) {
          column.length = 10
        }
      } else {
        column.length = null
      }

      // 重置自增
      if (!canAutoIncrement(column)) {
        column.autoIncrement = false
      }
    }

    // 主键变化
    const onPrimaryKeyChange = (column) => {
      if (column.primaryKey) {
        // 取消其他字段的主键
        tableForm.columns.forEach(col => {
          if (col !== column) {
            col.primaryKey = false
            col.autoIncrement = false
          }
        })
        // 主键不能为空
        column.nullable = false
      } else {
        // 取消自增
        column.autoIncrement = false
      }
    }

    // 添加索引
    const addIndex = () => {
      tableForm.indexes.push({
        name: '',
        type: 'INDEX',
        columns: []
      })
    }

    // 移除索引
    const removeIndex = (index) => {
      tableForm.indexes.splice(index, 1)
    }

    // 预览SQL
    const previewSQL = () => {
      const sql = generateSQL()
      emit('preview-sql', sql)
    }

    // 生成SQL
    const generateSQL = () => {
      if (props.databaseType === 'mysql') {
        return generateMySQLCreateSQL()
      } else {
        return generatePostgreSQLCreateSQL()
      }
    }

    // 生成MySQL创建表SQL
    const generateMySQLCreateSQL = () => {
      let sql = `CREATE TABLE \`${tableForm.name}\` (\n`
      
      // 字段定义
      const columnDefs = tableForm.columns.map(col => {
        let def = `  \`${col.name}\` ${col.type}`
        
        if (col.length && needsLength(col.type)) {
          def += `(${col.length})`
        }
        
        if (!col.nullable) {
          def += ' NOT NULL'
        }
        
        if (col.autoIncrement) {
          def += ' AUTO_INCREMENT'
        }
        
        if (col.defaultValue) {
          def += ` DEFAULT '${col.defaultValue}'`
        }
        
        if (col.comment) {
          def += ` COMMENT '${col.comment}'`
        }
        
        return def
      })
      
      sql += columnDefs.join(',\n')
      
      // 主键
      const primaryKey = tableForm.columns.find(col => col.primaryKey)
      if (primaryKey) {
        sql += `,\n  PRIMARY KEY (\`${primaryKey.name}\`)`
      }
      
      sql += '\n)'
      
      // 表选项
      sql += ` ENGINE=${tableForm.engine}`
      sql += ` DEFAULT CHARSET=${tableForm.charset}`
      sql += ` COLLATE=${tableForm.collation}`
      
      if (tableForm.comment) {
        sql += ` COMMENT='${tableForm.comment}'`
      }
      
      sql += ';'
      
      // 索引
      tableForm.indexes.forEach(index => {
        if (index.name && index.columns.length > 0) {
          sql += `\n\nCREATE ${index.type} \`${index.name}\` ON \`${tableForm.name}\` (\`${index.columns.join('`, `')}\`);`
        }
      })
      
      return sql
    }

    // 生成PostgreSQL创建表SQL
    const generatePostgreSQLCreateSQL = () => {
      let sql = `CREATE TABLE "${tableForm.name}" (\n`
      
      // 字段定义
      const columnDefs = tableForm.columns.map(col => {
        let def = `  "${col.name}" ${col.type}`
        
        if (col.length && needsLength(col.type)) {
          def += `(${col.length})`
        }
        
        if (!col.nullable) {
          def += ' NOT NULL'
        }
        
        if (col.defaultValue) {
          def += ` DEFAULT '${col.defaultValue}'`
        }
        
        return def
      })
      
      sql += columnDefs.join(',\n')
      
      // 主键
      const primaryKey = tableForm.columns.find(col => col.primaryKey)
      if (primaryKey) {
        sql += `,\n  PRIMARY KEY ("${primaryKey.name}")`
      }
      
      sql += '\n);'
      
      // 注释
      if (tableForm.comment) {
        sql += `\n\nCOMMENT ON TABLE "${tableForm.name}" IS '${tableForm.comment}';`
      }
      
      tableForm.columns.forEach(col => {
        if (col.comment) {
          sql += `\nCOMMENT ON COLUMN "${tableForm.name}"."${col.name}" IS '${col.comment}';`
        }
      })
      
      // 索引
      tableForm.indexes.forEach(index => {
        if (index.name && index.columns.length > 0) {
          const indexType = index.type === 'UNIQUE' ? 'UNIQUE INDEX' : 'INDEX'
          sql += `\n\nCREATE ${indexType} "${index.name}" ON "${tableForm.name}" ("${index.columns.join('", "')}");`
        }
      })
      
      return sql
    }

    // 保存表
    const saveTable = async () => {
      try {
        await tableFormRef.value.validate()
        
        if (!isValidTable.value) {
          ElMessage.warning('请完善表信息和字段定义')
          return
        }
        
        emit('save', { ...tableForm })
      } catch (error) {
        ElMessage.error('请检查表单信息')
      }
    }

    return {
      tableFormRef,
      tableForm,
      tableRules,
      dataTypes,
      isValidTable,
      needsLength,
      canAutoIncrement,
      addColumn,
      removeColumn,
      validateColumnName,
      onColumnTypeChange,
      onPrimaryKeyChange,
      addIndex,
      removeIndex,
      previewSQL,
      saveTable
    }
  }
}
</script>

<style scoped>
.table-designer {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.designer-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-info h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.designer-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.table-info-card,
.columns-card,
.indexes-card {
  :deep(.el-card__header) {
    padding: 12px 16px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }
  
  :deep(.el-card__body) {
    padding: 16px;
  }
}

.columns-header,
.indexes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.columns-table,
.indexes-table {
  margin-top: 8px;
}

.column-attributes {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>